package com.learn.xueer.app.util

import android.media.MediaPlayer
import java.util.Timer
import java.util.TimerTask

class MediaPlayerProgressListener(
    private val mediaPlayer: MediaPlayer?,
    private val progressListener: OnProgressListener
) {
    private var timer: Timer? = null
    private var timerTask: TimerTask? = null

    init {
        startProgressListener()
    }

    private fun startProgressListener() {
        timer = Timer()
        timerTask = object : TimerTask() {
            override fun run() {
                if (mediaPlayer != null && mediaPlayer.duration > 0) {
                    val currentProgress = mediaPlayer.currentPosition
                    // 这里可以调用方法处理当前播放进度，例如更新UI
                    onProgress(currentProgress)
                }
            }
        }
        timer!!.schedule(timerTask, 0, 1000) // 每秒更新一次进度
    }

    private fun onProgress(currentProgress: Int) {
        // 处理当前播放进度
        progressListener.onProgress(currentProgress)
    }

    fun stopProgressListener() {
        if (timerTask != null) {
            timerTask!!.cancel()
            timerTask = null
        }
        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
    }

    interface OnProgressListener {
        fun onProgress(progress: Int)
    }
}